package org.xiaom.butler.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xiaom.butler.bean.Hotel;
import org.xiaom.butler.bean.area.City;
import org.xiaom.butler.bean.area.Country;
import org.xiaom.butler.bean.area.County;
import org.xiaom.butler.bean.area.Province;
import org.xiaom.butler.service.BaseService;
import org.xiaom.butler.util.Standard;
import org.xiaom.butler.util.Util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class HotelServlet
 */
public class HotelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String SAVE_OR_UPDATE = "save_update";
	public static final String DELETE = "delete";
	public static final String LIST = "list";
	private BaseService hotelService;
	Country country=null;
	Gson gson = new GsonBuilder().create();
	public HotelServlet() {
		super();
	}

	@Override
	public void init() throws ServletException {
		this.hotelService = new BaseService(Hotel.class);
		super.init();
		String path = getServletContext().getRealPath("/") + "/r/config"
				+ "/json-area.txt";
		InputStreamReader r = null;
		try {
			r = new InputStreamReader(new FileInputStream(path));
			country = gson.fromJson(r, Country.class); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				r.close();
			} catch (IOException e) {
			}
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String url = request.getRequestURI();
		boolean requestExactly=true;
		String function = url.split("\\.")[1];
		String name = url.split("/hotel/")[1];
		if (function.equals("do")) { // 请求是个功能性请求
			if ("add.do".equals(name)) {
				add(request, response);
				goToList(request, response, Standard.REDIRECT);
			} else if ("delete.do".equals(name)) {
				delete(request, response);
				goToList(request, response, Standard.REDIRECT);
			} else if ("edit.do".equals(name)) {
				edit(request, response);
				goToList(request, response, Standard.REDIRECT);
			} else if("levelUp.do".equals(name)){
				levelUp(request,response);
				goToList(request, response, Standard.REDIRECT);
			} else {
				requestExactly=false;
			}
		} else if (function.equals("jsp")) {// 要求显示页面
			if (name.equals("add.jsp")) {
				forwardToAdd(request, response, null); 
			} else if (name.equals("list.jsp")) {
				goToList(request, response, Standard.FORWARD);
			} else if (name.equals("edit.jsp")) {
				goToEdit(request, response, Standard.FORWARD);
			} else if(name.equals("country.jsp")){
				response.getWriter().write(gson.toJson(country));
			} else if(name.equals("province.jsp")){
				response.getWriter().write(gson.toJson(country.province)); 
			} else if(name.equals("city.jsp")){
				String pId=Util.getQueryParam(request, "province", "01");
				for(Province p:country.province){
					if(pId.equalsIgnoreCase(p.id)){
						response.getWriter().write(gson.toJson(p.city));
					}
				}
			} else if(name.equals("county.jsp")){
				String cityId=Util.getQueryParam(request, "city", "0101");
				for(Province p:country.province){
					for(City c:p.city){
						if(cityId.equalsIgnoreCase(c.id)){
							response.getWriter().write(gson.toJson(c.county));
						}
					}
				}
			} else {
				requestExactly=false;
			}
		}else{
			requestExactly=false;
		}
		if(!requestExactly){
			String msg="没找到页面";
			Util.redirectToErrorPage(request, response, msg);
		}
	}

	private void levelUp(HttpServletRequest request,
			HttpServletResponse response) {
		String id=Util.getQueryParam(request, "id", null);
		Hotel h =(Hotel) hotelService.get(Integer.parseInt(id));
		h.setVersion(h.getVersion()+1);
		hotelService.saveOrUpdate(h);
	}

	private void goToEdit(HttpServletRequest request,
			HttpServletResponse response, boolean forward) {
		Hotel bean =(Hotel) hotelService.get(Integer.parseInt(Util.getQueryParam(request, "id", "")));
		request.setAttribute("bean", bean);
		for(Province p:country.province){
			for(City c:p.city){
				for(County ct:c.county){
					if(ct.weatherCode.equalsIgnoreCase(bean.getCityNumber())){
						request.setAttribute("city_name", ct.name);
					}
				}
			}
		}
		request.setAttribute("country", country);
		Util.forward(getServletConfig().getServletContext(), request, response,
				"hotel/edit.jsp", false);
	}
	private void edit(HttpServletRequest request, HttpServletResponse response) {
		try {
			String id=Util.getQueryParam(request, "id", null);
			String cityNumber = Util.getQueryParam(request, "city_number", null);
			String name = Util.getQueryParam(request, "name", null);
			String phone = Util.getQueryParam(request, "phone", null);
			String imagePath=Util.getQueryParam(request, "image_path", null);
			String versionStr=Util.getQueryParam(request, "version",null);
			Integer version=null;
			try{
				version=Integer.parseInt(versionStr);
			}catch (Exception e){}
			Hotel h =(Hotel) hotelService.get(Integer.parseInt(id));

			if(cityNumber!=null){
				h.setCityNumber(cityNumber);
			}
			if(name!=null){
				h.setName(name);
			}
			if(phone!=null){
				h.setPhone(phone);
			}
			if(imagePath!=null){
				h.setImagePath(imagePath);
			}
			if(version!=null){
				h.setVersion(version);
			}

			hotelService.saveOrUpdate(h);
		} catch (Exception e) {
			e.printStackTrace();
			Util.redirectToErrorPage(request, response, "保存错误。请检查输入");
		}
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		try {
			String cityNumber = Util.getQueryParam(request, "city_number", "");
			String name = Util.getQueryParam(request, "name", "");
			String phone = Util.getQueryParam(request, "phone", "");
			String imagePath=Util.getQueryParam(request, "image_path", "");
			Hotel h = new Hotel();
			h.setCityNumber(cityNumber);
			h.setName(name);
			h.setPhone(phone);
			
			h.setImagePath(imagePath);
			hotelService.saveOrUpdate(h);
		} catch (Exception e) {
			e.printStackTrace();
			Util.redirectToErrorPage(request, response, "保存错误。请检查输入");
		}
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) {
		JsonObject jo = new JsonObject();
		try {
			String id = (String) request.getParameter("id");
			hotelService.delete(Integer.parseInt(Util.getQueryParam(request,"id", "")));
			jo.addProperty("state", "success");
			response.getWriter().write(jo.toString());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().write("{state:faild}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	private void getOne(HttpServletRequest request, HttpServletResponse response) {

	}

	private void goToList(HttpServletRequest request,
			HttpServletResponse response, boolean mode)
			throws ServletException, IOException {
		// response.sendRedirect(Standard.JSP_PATH_PREFIX+"hotel/list.jsp" );
		List<Hotel> list = hotelService.getList("from Hotel");
		request.setAttribute("bean_list", list);
		String path = "hotel/list.jsp";
		if (Standard.FORWARD == mode) {
			Util.forward(getServletConfig().getServletContext(), request,
					response, path, false);
		} else {
			Util.redirect(request, response, "list.jsp", false);
		}
	}

	private void forwardToAdd(HttpServletRequest request,
			HttpServletResponse response, Hotel bean) throws ServletException,
			IOException {
		request.setAttribute("country", country);
		Util.forward(getServletConfig().getServletContext(), request, response,
				"hotel/add.jsp", false);
	}
}
